package de.koller.reason.render.state;

import de.koller.reason.ReasonRoot;
import de.koller.reason.render.obj.Polygon;
import de.koller.reason.render.obj.Texture;
import de.koller.reason.render.obj.Vertex;
import java.util.ArrayList;
import java.util.List;

public class RGL {

	private Texture texture;
	private final ReasonRoot rroot;

	public RGL( ReasonRoot rroot ) {
		this.rroot = rroot;
	}
	
	public RGLPrimitivState begin( PrimitivType type ) {
		return new RGLPrimitivState( type );
	}
	
	public void bind( Texture texture ) {
		this.texture = texture;
	}
	
	public class RGLPrimitivState {
		private final PrimitivType type;
		
		private final List<Vertex> verteces = new ArrayList<>();
		private int currentColor = 0xffffffff;

		private RGLPrimitivState( PrimitivType type ) {
			this.type = type;
		}
		
		public RGLPrimitivState vertex( float x, float y, float z ) {
			Vertex v = new Vertex( x, y, z );
			v.color = currentColor;
			verteces.add( v );
			return this;
		}
	
		public RGLPrimitivState color( int color ) {
			verteces.get( verteces.size()-1 ).color = color;
			currentColor = color;
			return this;
		}
		
		public RGLPrimitivState uvw( float u, float v ) {
			verteces.get( verteces.size()-1 ).uvw.set( u, v, 0 );
			return this;
		}
		
		public void end() {
			if( type == PrimitivType.Triangle )
				renderPolygon( 0, 1, 2 );
			else if( type == PrimitivType.Quad ) {
				renderPolygon( 0, 1, 3 );
				renderPolygon( 1, 2, 3 );
			}
		}
	
		private void renderPolygon( int i0, int i1, int i2 ) {
			Polygon p = new Polygon( verteces.get( i0 ),
									 verteces.get( i1 ),
									 verteces.get( i2 ) );
			p.texture = RGL.this.texture;
			rroot.rRender.renderPolygon( p );
		}
	}
	
	public static enum PrimitivType {
		Triangle( 3 ), Quad( 4 );
		
		private final int verteces;

		private PrimitivType( int verteces ) {
			this.verteces = verteces;
		}
	}
	
}
